//
//  PLYearMonthPicker.m
//
//  Created by KimmanYip on 2018/3/15.
//

#import "PLYearMonthPicker.h"
#import "PLColor.h"
#import "UIView+PLExtension.h"
#import "Masonry.h"
#import "DateTools.h"

static const CGFloat kViewHeight = 273;

static const NSInteger StartYear = 1900;
static const NSInteger EndYear   = 2100;

typedef void(^DPCompletionBlock)(NSString *dateString);

typedef NS_ENUM(NSInteger, Component) {
    ComponentYear = 0,
    ComponentMonth,
};

@interface PLYearMonthPicker ()<UIPickerViewDelegate, UIPickerViewDataSource>
{
    NSMutableArray *years;
    NSArray *months;
    NSArray *minMonths; // 最开始时的月份
    
    NSInteger defaultYearRow;
    NSInteger defaultMonthRow;
    NSInteger currentYearRow;
}

@property (nonatomic, strong) UIView        *contentView;
@property (nonatomic, strong) UIPickerView  *picker;

@property (nonatomic, copy) DPCompletionBlock completion;
@property (nonatomic, copy) NSString *formatter;

// 最值，为空时用默认值
@property (nonatomic, strong) NSDate *minDate;    // 开始时间
@property (nonatomic, strong) NSDate *maxDate;    // 结束时间

// 限制到当前时间
@property (nonatomic, assign) BOOL          limitToCurrent;

@end

@implementation PLYearMonthPicker

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.limitToCurrent = YES;
        [self initData];
        [self buildUI];
    }
    return self;
}

- (instancetype)initWithCompletion:(void(^)(NSString *dateString))completion
{
    return [self initWithFormatter:@"yyyy-MM" completion:completion];
}

- (instancetype)initWithMinDate:(NSDate *)minDate maxDate:(NSDate *)maxDate completion:(void(^)(NSString *))completion {
    self = [super init];
    if (self) {
        self.minDate = minDate;
        self.maxDate = maxDate;
        self.formatter = @"yyyy-MM";
        self.completion = completion;
        self.limitToCurrent = NO;
        [self initData];
        [self buildUI];
    }
    return self;
}

- (instancetype)initWithFormatter:(NSString *)formatter completion:(void(^)(NSString *dateString))completion {
    self = [super init];
    if (self) {
        self.formatter = formatter;
        self.completion = completion;
        self.limitToCurrent = NO;
        [self initData];
        [self buildUI];
    }
    return self;
}

- (void)initData
{
    years = [NSMutableArray array];
    
    NSInteger min = self.minDate ? self.minDate.year : StartYear;
    NSInteger max = self.maxDate ? self.maxDate.year : EndYear;
    
    for (NSInteger i = min; i <= max; i++) {
        [years addObject:[NSString stringWithFormat:@"%ld年", (long)i]];
    }
    
    months = [[NSArray alloc] initWithObjects:
              @"1月", @"2月", @"3月", @"4月",
              @"5月", @"6月", @"7月", @"8月",
              @"9月", @"10月", @"11月", @"12月",
              nil];
    
    minMonths = months;
    if (self.minDate) {
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(self.minDate.month-1, 13-self.minDate.month)];
        minMonths = [months objectsAtIndexes:set];
    }
}

- (void)show {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:self];
        [keyWindow endEditing:YES];
        [self showAnimation];
    });
}

- (void)showAnimation {
    self.contentView.y = self.frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.y = self.frame.size.height-kViewHeight;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.y = self.frame.size.height;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)buildUI
{
    self.frame = [UIScreen mainScreen].bounds;
    
    // 背景半透明
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    self.contentView = [UIView new];
    [self.contentView setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kViewHeight);
        make.left.right.and.bottom.equalTo(self);
    }];
    
    
    // 顶部
    UIView *topView = [UIView new];
    topView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.left.top.and.right.equalTo(self.contentView);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"时间日期";
    titleLabel.textColor = ColorWithHex(0x303030);
    titleLabel.font = [UIFont systemFontOfSize:18];
    [topView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(topView);
    }];
    
    UIView *lineV = [UIView new];
    [lineV setBackgroundColor:ColorWithHex(0xEFF1F0)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    [topView addSubview:lineV];
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.equalTo(topView);
        make.height.mas_equalTo(0.5);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:ColorWithHex(0xcccccc) forState:UIControlStateNormal];
    [cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [cancelBtn addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:cancelBtn];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.and.bottom.equalTo(topView);
        make.width.mas_equalTo(55);
    }];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn setTitle:@"完成" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:ColorWithHex(0xBA8833) forState:UIControlStateNormal];
    [confirmBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [confirmBtn addTarget:self action:@selector(confirmButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:confirmBtn];
    
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.and.bottom.equalTo(topView);
        make.width.mas_equalTo(55);
    }];
    
    //  选择器
    self.picker = [UIPickerView new];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.contentView addSubview:self.picker];
    [self.picker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.contentView);
        make.top.equalTo(topView.mas_bottom);
        make.bottom.equalTo(self);
    }];
    
    [self setPickerDefaultValue];
}

- (void)setPickerDefaultValue {
    NSDate *date =  [NSDate date];
    if (self.maxDate) {
        date = self.maxDate;
    } else if (self.minDate) {
        date = self.minDate;
    }
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
    NSInteger year = cmp.year;
    NSInteger month = cmp.month;
    if (self.minDate) {
        month = 1;
    }
    
    [self setDefaultYear:year month:month];
}

- (void)setDefaultYear:(NSInteger)year month:(NSInteger)month {
    NSInteger min = self.minDate ? self.minDate.year : StartYear;
    defaultYearRow = year - min;
    defaultMonthRow = month - 1;
    currentYearRow = defaultYearRow;
    
    [self.picker selectRow:defaultYearRow inComponent:ComponentYear animated:NO];
    [self.picker selectRow:defaultMonthRow inComponent:ComponentMonth animated:NO];
}

#pragma mark - Action
- (void)cancelButtonAction
{
    [self dismiss];
}

- (void)confirmButtonAction
{
    NSInteger min = self.minDate ? self.minDate.year : StartYear;
    NSInteger year = [self.picker selectedRowInComponent:ComponentYear] + min;
    NSInteger month = [self.picker selectedRowInComponent:ComponentMonth] + 1;
    if (self.minDate && year == self.minDate.year) {
        month = self.minDate.month+[self.picker selectedRowInComponent:ComponentMonth];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(yearMonthPickerDidSelectYear:month:)]) {
        [self.delegate yearMonthPickerDidSelectYear:year month:month];
    }
    
    if (self.completion) {
        NSDate *date = [NSDate dateWithYear:year month:month day:2];
        self.completion([date formattedDateWithFormat:self.formatter]);
    }
    
    [self dismiss];
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == ComponentYear) {
        if (self.limitToCurrent) {
            return defaultYearRow+1;
        } else {
            return years.count;
        }
    } else if (component == ComponentMonth) {
        if (self.limitToCurrent) {
            if ([self.picker selectedRowInComponent:ComponentYear]  == defaultYearRow || currentYearRow == defaultYearRow) {
                return defaultMonthRow+1;
            } else {
                return months.count;
            }
        } else {
            if (([self.picker selectedRowInComponent:ComponentYear]  == defaultYearRow || currentYearRow == defaultYearRow) && self.maxDate) {
                return self.maxDate.month;
            } else if (([self.picker selectedRowInComponent:ComponentYear]  == defaultYearRow || currentYearRow == defaultYearRow) && self.minDate) {
                return minMonths.count;
            } else {
                return months.count;
            }
        }
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 100.f;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == ComponentYear) {
        return [years objectAtIndex:row];
    } else if (component == ComponentMonth) {
        if (([self.picker selectedRowInComponent:ComponentYear]  == defaultYearRow || currentYearRow == defaultYearRow) && self.minDate) {
            return [minMonths objectAtIndex:row];
        } else {
            return [months objectAtIndex:row];
        }
    }
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == ComponentYear) {
        currentYearRow = row;
    }
    [pickerView reloadComponent:ComponentMonth];
}

#pragma mark - Getter & Setter
- (void)setDefaultDate:(NSString *)defaultDate {
    NSArray *component = [defaultDate componentsSeparatedByString:@"-"];
    if (component.count == 2) {
        NSInteger year = [[component firstObject] integerValue];
        NSInteger month = [[component lastObject] integerValue];
        [self setDefaultYear:year month:month];
    }
}


@end
